from datetime import datetime
import json
from django.views.decorators.http import require_POST, require_GET
from django.views.decorators.csrf import csrf_exempt
from tanxi.client.Handler.JsonResponse import create_response
from tanxi.client.Handler.Logger import log_error, log_info
from django.conf import settings

# 数据库选择
if settings.DATABASE_TYPE == 'mysql':
    from tanxi.client.utils.mysql.travels_mysql import TravelBlogUpdateHandler, TravelBlogQueryHandler
elif settings.DATABASE_TYPE == 'sqlite':
    # from tanxi.client.utils.sqlite.travel_sqlite import TravelBlogUpdateHandler, TravelBlogQueryHandler 
    pass
else:
    raise ValueError("Unsupported database type specified in settings.")

# 初始化处理器
travel_query = TravelBlogQueryHandler()
travel_update = TravelBlogUpdateHandler()

@require_GET
@csrf_exempt
def get_travel_blogs(request):
    """获取旅游博客列表"""
    try:
        blog_id = request.GET.get('id')
        city = request.GET.get('city')
        title = request.GET.get('title')
        author_id = request.GET.get('author_id')
        is_published = request.GET.get('is_published')

        if blog_id or city or title or author_id or is_published:
            blogs = travel_query.query_travel_blogs(
                id=blog_id,
                city=city,
                title=title,
                author_id=author_id,
                is_published=is_published
            )
            blogs = list(blogs)
            log_info(f"按参数查询旅游博客结果: {blogs}")
        else:
            blogs = travel_query.query_travel_blogs()
            blogs = list(blogs)
            log_info(f"查询所有旅游博客结果: {blogs}")
        
        return create_response(code=200, message="Success", remarks="查询成功", data=blogs)
    except Exception as e:
        log_error(f"查询旅游博客出错: {str(e)}")
        return create_response(code=500, message="Error", remarks="查询失败", data=None)

@require_POST
@csrf_exempt
def write_travel_blog(request):
    """创建或更新旅游博客"""
    try:
        data = json.loads(request.body)
        log_info(f"接收到的旅游博客数据: {data}")

        # 处理必填字段和默认值
        blog_data = {
            'city': data.get('city', ''),
            'title': data.get('title', ''),
            'address': data.get('address', ''),
            'description': data.get('description', ''),
            'image': data.get('image', ''),
            'map_url': data.get('map_url', ''),
            'is_published': data.get('is_published', False),
            'author_id': data.get('author_id'),
            'tags': data.get('tags', []),
            'view_count': data.get('view_count', 0)
        }

        # 处理ID
        if 'id' in data and data['id']:
            blog_data['id'] = data['id']

        # 调用处理器
        result = travel_update.update_or_create_travel_blog(blog_data)
        return create_response(code=200, message="Success", remarks="操作成功", data=result)

    except json.JSONDecodeError:
        return create_response(code=400, message="Error", remarks="请求体不是有效的JSON格式", data=None)
    except ValueError as e:
        return create_response(code=400, message="Error", remarks=str(e), data=None)
    except Exception as e:
        log_error(f"操作旅游博客出错: {str(e)}")
        return create_response(code=500, message="Error", remarks="服务器内部错误", data=None)

@require_POST
@csrf_exempt
def delete_travel_blog(request):
    """删除旅游博客"""
    try:
        data = json.loads(request.body)
        blog_id = data.get('blog_id')
        if not blog_id:
            return create_response(code=400, message="Error", remarks="缺少blog_id参数", data=None)
        
        success = travel_update.delete_travel_blog(blog_id)
        if success:
            return create_response(code=200, message="Success", remarks="删除成功", data=None)
        else:
            return create_response(code=404, message="Error", remarks="旅游博客不存在", data=None)
    except Exception as e:
        log_error(f"删除旅游博客出错: {str(e)}")
        return create_response(code=500, message="Error", remarks="服务器内部错误", data=None)